package com.fingard.dsp.bank.directbank.weixin01;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.fingard.common.utils.json.JSONUtils;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IJSAPIOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqGenGetUserCodeURL;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqGenRealNameURL;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqUnifiedOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsGenGetUserCodeURL;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsGenRealNameURL;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsUnifiedOrder;
import com.fingard.io.FileHelper;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.HttpClientUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class WEIXIN01JSAPIOrder extends WxUnifiedOrder implements IJSAPIOrder {

	public RetAtsUnifiedOrder submitJSAPIOrder(ReqUnifiedOrder p_req) {
		return submitUnifiedOrder(p_req);
	}

	public RetAtsQueryOrder queryJSAPIPay(ReqQueryOrder p_req) {
		return queryUnifiedOrder(p_req);
	}

	public RetAtsGenGetUserCodeURL GenGetUserCodeURL(ReqGenGetUserCodeURL p_req) {
		RetAtsGenGetUserCodeURL retAts = new RetAtsGenGetUserCodeURL();
		try {
			ActSetItem actItem = this.getBankConfig().getActSetItemByAny(p_req.ownAct, p_req.merchantId, p_req.appId,
					"unifiedorder");
			if (actItem != null) {
				String appid = p_req.appId;
				if (StringHelper.isNullOrEmpty(appid)) {
					appid = actItem.appId;
				}
				String mch_id = p_req.merchantId;
				if (StringHelper.isNullOrEmpty(mch_id)) {
					mch_id = actItem.merchantId;
				}

				String authUrl = bankFront.getUrl("authUrl");// 微信公众号授权URL
				if (StringHelper.hasAnyChar(authUrl)) {
					String authRedirectUri = p_req.authRedirectUri;
					if (StringHelper.isNullOrEmpty(authRedirectUri)) {
						authRedirectUri = bankFront.getUrl("authRedirectUri");// 微信公众号授权回调地址
					}
					if (StringHelper.hasAnyChar(authRedirectUri)) {
						authUrl = authUrl + "?appid=" + appid + "&redirect_uri="
								+ java.net.URLEncoder.encode(authRedirectUri, this.getCharset())
								+ "&response_type=code&scope=snsapi_base&state=" + p_req.urid + "#wechat_redirect";
						retAts.respCode = "0";
						retAts.respInfo = "成功";
						retAts.getUserCodeURL = authUrl;
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = "未找到授权回调地址";
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = "未找到授权URL";
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		return retAts;
	}

	@Override
	public RetAtsGenRealNameURL genRealNameURL(ReqGenRealNameURL p_req) {
		RetAtsGenRealNameURL retAts = new RetAtsGenRealNameURL();
		try {
			ActSetItem actItem = this.getBankConfig().getActSetItemByAny(p_req.ownAct, p_req.merchantId, p_req.appId,
					"unifiedorder");
			if (actItem != null) {
				String appid = p_req.appId;
				if (StringHelper.isNullOrEmpty(appid)) {
					appid = actItem.appId;
				}
				String mch_id = p_req.merchantId;
				if (StringHelper.isNullOrEmpty(mch_id)) {
					mch_id = actItem.merchantId;
				}
				String openId = p_req.openId;

				String authUrl = bankFront.getUrl("realNameAuthUrl");
				if (StringHelper.hasAnyChar(authUrl)) {
					String authRedirectUri = p_req.authRedirectUri;
					if (StringHelper.hasAnyChar(authRedirectUri)) {
						authUrl = authUrl + "?openid=" + openId + "&mch_id=" + mch_id + "&redirect_url="
								+ java.net.URLEncoder.encode(authRedirectUri, this.getCharset()) + "&app_id=" + appid;
						retAts.respCode = "0";
						retAts.respInfo = "成功";
						retAts.getRealNameAuthURL = authUrl;
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = "未找到授权回调地址";
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = "未找到授权URL";
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		return retAts;
	}

    /**
     * 获取用户ID
     *
     * 参考文档在线地址：https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839
     * 参考接口：第三步：使用auth_code换取接口access_token及用户userId
     */
    @Override
    public RetAtsGenGetUserCodeURL getUserId(ReqGenGetUserCodeURL p_req) {
        RetAtsGenGetUserCodeURL retAts = new RetAtsGenGetUserCodeURL();

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req.ownAct, "unifiedorder");
            if(actItem != null){
				String respCode = "0";
				StringBuilder respInfo = new StringBuilder();
				String userinfos = "";
				if (StringHelper.isNullOrEmpty(actItem.appSecret) ) {
					respCode = "-1";
					respInfo.append("未设置 账号[" + p_req.ownAct + "]商户配置的appSecret参数 !\r\n");
				}

				if (StringHelper.isNullOrEmpty(actItem.appId)) {
					respCode = "-1";
					respInfo.append( "未设置 账号[" + p_req.ownAct + "]商户配置的appId参数 !\r\n");
				}

				String tmpUrl = bankFront.getUrl("getUserInfo");

				if (StringHelper.isNullOrEmpty(tmpUrl)) {
					respCode = "-1";
					respInfo.append("未设置“获取用户基本信息(UnionID机制)”的地址,请检查BankFront.xml相关配置!\r\n");
				}
				if (StringHelper.isNullOrEmpty(p_req.openid)) {
					respCode = "-1";
					respInfo.append("传入参数Openid值为空!\r\n");
				}
				if ("-1".equals(respCode)) {
					retAts.respCode = respCode;
					retAts.respInfo = respInfo.toString();
					return retAts;
				}

				String[] tmpRes = getAccessToken(actItem.appId, actItem.appSecret);
				if (!"".equals(tmpRes[0])) {
					retAts.respCode = "-1";
					retAts.respInfo = tmpRes[1];
					return retAts;
				}
				String accessToken = tmpRes[1];
				String[] openids = p_req.openid.split(",");

				String[] tmpRet = null;

                //批量获取用户基本信息
                tmpUrl = tmpUrl + "?access_token=" + accessToken;
                WriteBankUrlLogLn(tmpUrl);
                WebRequest tmpWebRequest = new WebRequest(tmpUrl);
                JSONObject jsonRequest = new JSONObject();
                JSONArray jsonBody = new JSONArray();

                for (String openid : openids) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("openid", openid);
                    jsonObject.put("lang", "zh_CN");
                    jsonBody.add(jsonObject.toString());
                }
                jsonRequest.put("user_list", jsonBody.toString());
                String bizContent = JSON.toJSONString(jsonRequest);
                WriteBankLogStep2(bizContent);
                byte[] tmpUpBytes = bizContent.getBytes(getCharset());
                tmpRet = tmpWebRequest.upload(tmpUpBytes, getCharset());


				if (tmpRet[0].length() == 0) {
					WriteBankLogStep3(tmpRet[1]);
					if (tmpRet[1].startsWith("{")) {
						Map<String, String> retMap = new HashMap<String,String>();
						retMap = JSONUtils.json2Map(tmpRet[1]);
						respCode = "0";
						if (retMap.containsKey("errcode")||retMap.containsKey("errmsg")) {
							//查询有错误返回错误  {"errcode":40013,"errmsg":"invalid appid"}
							respCode = "-1";
							String errcode = retMap.get("errcode");
							String errmsg = retMap.get("errmsg");
							respInfo.append(StringHelper.joinNotEmpty("-", errcode, errmsg));
						} else {
							//成功则返回S3字符串
							respCode = "0";
							userinfos=tmpRet[1];
							respInfo.append("查询成功");
						}
					} else {
						respCode = "-1";
						respInfo.append(tmpRet[1]);
					}
				} else {
					respCode = "-1";
					respInfo.append(tmpRet[1]);
					WriteBankLogLn(tmpRet[0] + "\r\n" + tmpRet[1]);
				}
				retAts.respCode = respCode;
				retAts.respInfo = respInfo.toString();
				retAts.userinfos = userinfos;
				return retAts;
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息!";
            }
        } catch(Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        return retAts;
    }

}
